#!/bin/bash
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Install grub to disk. Only used in x86 based platforms

if ! is_x86; then
  return 0
fi

export DEBIAN_FRONTEND="noninteractive"

DI_BOOTLOADER=$(installer_get "DI_BOOTLOADER")
DI_CUR_RESOLUTION=$(installer_get "DI_CUR_RESOLUTION")
DI_HOST_DEV=$(installer_get "DI_HOST_DEV")
DI_LUPIN=$(installer_get "DI_LUPIN")
DI_UEFI=$(installer_get "DI_UEFI")

# if no DI_BOOTLOADER, treat as not installing bootloader
[ -z ${DI_BOOTLOADER} ] && \
  warn_exit "DI_BOOTLOADER not set. Treat as not install bootloader. Skip."

if [ x${DI_UEFI} = xtrue ]; then
  BOOT="uefi"
else
  BOOT="legacy"
fi

# Check SecureBoot option is enabled or not.
if [ x${BOOT} = xuefi ]; then
  SB=/sys/firmware/efi/vars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c/data
  value=$(od -An -t u1 "${SB}" 2>/dev/null | sed s/[[:space:]]//g)
  [ x${value} = x1 ] && echo "uefi-secure-boot detected"
fi

case ${BOOT} in
  "legacy")
    echo "INFO: Detected legacy machine, installing grub to ${DI_BOOTLOADER}"
    install_package grub-pc

    if [ x${DI_LUPIN} = xtrue ]; then
      echo "Fix grub install failed in lupin"
      [ -d /boot/grub ] || mkdir /boot/grub
      echo "(hd0) ${DI_BOOTLOADER}" > /boot/grub/device.map
      mkdir /host
      mount ${DI_HOST_DEV} /host
      echo "Mount DI_HOST_DEV: " ${DI_HOST_DEV}
    fi

    grub-install --no-floppy ${DI_BOOTLOADER} --target=i386-pc --force 2>/dev/null || true
    ;;

  "uefi")
    # try to get efi architecture
    if [ x$(cat /sys/firmware/efi/fw_platform_size 2>/dev/null) = 'x32' ]; then
      install_package grub-efi-ia32
      add_start_option --target=i386-efi --efi-directory=/boot/efi

    else
      # Clover efi loader cannot use grub.efi correctly,
      # so we may patch grub or use grub.efi.signed.
      install_package shim-signed grub-efi-amd64-signed efibootmgr

      mount -t efivarfs efivarfs /sys/firmware/efi/efivars
      rm /sys/firmware/efi/efivars/dump-*

      # uefi-secure-boot options is enabled by default
      add_start_option --target=x86_64-efi --uefi-secure-boot
      umount /sys/firmware/efi/efivars
    fi

    ;;
esac

# Try to avoid kernel update error when create symbol link
case ${BOOT} in
  "uefi")
    echo "# avoid kernel update fails with /boot on FAT32
do_symlinks = no" | tee /etc/kernel-img.conf
    ;;
esac

case ${BOOT} in
  uefi*)
    echo "Try to fix efi boot order to deepin first"
    fix_boot_order
    ;;
  legacy)
    ;;
  *)
    ;;
esac

if [[ $(cat /proc/cmdline) =~ \ nomodeset(\ |$) ]];
then
    nomodeset="nomodeset"
fi

GRUB_TIMEOUT=$(installer_get "grub_timeout")
GRUB_TIMEOUT=${GRUB_TIMEOUT:-1}

cat >> /etc/default/grub << EOF
# Generated by deepin-installer
GRUB_BACKGROUND="/boot/grub/themes/deepin/background.png"
GRUB_CMDLINE_LINUX_DEFAULT="splash quiet $nomodeset"
GRUB_DEFAULT=0
GRUB_DISTRIBUTOR="\`/usr/bin/lsb_release -d -s 2>/dev/null || echo UOS 20\`"
GRUB_THEME="/boot/grub/themes/deepin/theme.txt"
GRUB_TIMEOUT=${GRUB_TIMEOUT}
GRUB_GFXMODE=${DI_CUR_RESOLUTION}
DEEPIN_GFXMODE_DETECT=1
EOF

# Remove partman/ignore_uefi if that file is created by installer.
# See partman/os_prober.cpp for more info.
#IGNORE_UEFI=/var/lib/partman/ignore_uefi
#if [ -f $IGNORE_UEFI ] && [ x$(cat $IGNORE_UEFI) = 'xdeepin-installer' ]; then
#  rm -f $IGNORE_UEFI
#fi

# grub edit password
GRUB_PASSWORD=$(installer_get "DI_GRUB_PASSWORD")
USERNAME=$(installer_get "DI_USERNAME")
if [ -n "$GRUB_PASSWORD" ];then
cat > /etc/grub.d/01_grub_password <<EOF
#!/bin/sh
set -e
cat << P_EOF
set superusers="${USERNAME}"
password_pbkdf2 ${USERNAME} ${GRUB_PASSWORD}
P_EOF
EOF

# 暂时没有其他办法，因为不加--unrestricted参数的话，引导系统将需要提供密码
cat > /etc/grub.d/99_update_grub <<GRUB_EOF
#!/bin/sh
set -e
cat > /tmp/.update-grub <<EOF
#!/bin/sh
sleep 2
sed -i "s/\(menuentry '.*'\) -/\1 --unrestricted -/" /boot/grub/grub.cfg
EOF
chmod +x /tmp/.update-grub
/tmp/.update-grub &
GRUB_EOF

chmod +x /etc/grub.d/01_grub_password
chmod +x /etc/grub.d/99_update_grub
fi

# update grub theme
if [ x${DI_LUPIN} != xtrue ]; then
  DISPLAY_PORT=$(installer_get "DI_DISPLAY_PORT")
  export XAUTHORITY=/var/run/lightdm/root/${DISPLAY_PORT}
  export DISPLAY=${DISPLAY_PORT}
  LC_ALL="" LANGUAGE=$(installer_get "DI_LOCALE") LANG=$(installer_get "DI_LOCALE").UTF-8 /usr/lib/deepin-daemon/grub2 -prepare-gfxmode-detect
fi

# update grub config
update_grub_local
